package com.mobileserver.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONStringer;

import com.mobileserver.dao.BookClassDAO;
import com.mobileserver.dao.BookDAO;
import com.mobileserver.domain.Book;
import com.mobileserver.domain.BookClass;
import com.mobileserver.util.DBUtil;
 
public class BookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private BookDAO bookDAO = new BookDAO();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String action = request.getParameter("action");
		if(action.equals("query")) {
			String barcode = request.getParameter("barcode");
			barcode = barcode==null?"":new String(request.getParameter("barcode").getBytes("iso-8859-1"),"UTF-8");
			String bookName = request.getParameter("bookName");
			bookName = bookName==null?"":new String(request.getParameter("bookName").getBytes("iso-8859-1"),"UTF-8");
			int bookClassId = 0;
			if(request.getParameter("bookClassId") != null)
				bookClassId = Integer.parseInt(request.getParameter("bookClassId"));
			Timestamp publishDate = null;
			if(request.getParameter("publishDate")!=null)
				publishDate = Timestamp.valueOf(request.getParameter("publishDate"));
			List<Book> bookList = bookDAO.QueryBook(barcode,bookName,bookClassId,publishDate); 
			 
			StringBuffer sb = new StringBuffer();
			sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>").append("\r\n").append("<Books>").append("\r\n");
			for(int i = 0; i<bookList.size(); i++) {
				sb.append("	<Book>").append("\r\n")
					.append("		<barcode>").append(bookList.get(i).getBarcode()).append("</barcode>").append("\r\n")
					.append("		<bookName>").append(bookList.get(i).getBookName()).append("</bookName>").append("\r\n")
					.append("		<bookClassId>").append(bookList.get(i).getBookClassId()).append("</bookClassId>").append("\r\n")
					.append("		<price>").append(bookList.get(i).getPrice()).append("</price>").append("\r\n")
					.append("		<count>").append(bookList.get(i).getCount()).append("</count>").append("\r\n")
					.append("		<publishDate>").append(bookList.get(i).getPublishDate()).append("</publishDate>").append("\r\n")
					.append("		<bookImage>").append(bookList.get(i).getBookImage()).append("</bookImage>").append("\r\n")
				.append("	</Book>").append("\r\n");
			}
			sb.append("</Books>").append("\r\n");
		 
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(sb.toString());
		} else if(action.equals("add")) { 
			/*获取参数*/
			String barcode = new String(request.getParameter("barcode").getBytes("iso-8859-1"),"UTF-8"); 
			int bookClassId = Integer.parseInt(request.getParameter("bookClassId")); 
			String bookImage = new String(request.getParameter("bookImage").getBytes("iso-8859-1"),"UTF-8"); 
			String bookName = new String(request.getParameter("bookName").getBytes("iso-8859-1"),"UTF-8"); 
			int count = Integer.parseInt(request.getParameter("count")); 
			float price = Float.parseFloat(request.getParameter("price"));
			Timestamp publishDate = Timestamp.valueOf(request.getParameter("publishDate"));
		  
			/*封装对象*/
			Book book = new Book();
			book.setBarcode(barcode);
			book.setBookClassId(bookClassId);
			book.setBookImage(bookImage);
			book.setBookName(bookName);
			book.setCount(count);
			book.setPrice(price);
			book.setPublishDate(publishDate);
			
			/*调用业务层执行添加添加*/
			String result = bookDAO.AddBook(book); 
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(result);
		} else if(action.equals("delete")) {
			String barcode = new String(request.getParameter("barcode").getBytes("iso-8859-1"),"UTF-8");
			BookDAO bookDAO = new BookDAO();
			String result = bookDAO.DeleteBook(barcode);
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(result);
		} else if(action.equals("updateQuery")) {
			String barcode = new String(request.getParameter("barcode").getBytes("iso-8859-1"),"UTF-8");
			BookDAO bookDAO = new BookDAO();
			Book book = bookDAO.GetBook(barcode);
		 
			//客户端查询对象信息，返回json数据格式
			//将List<Person>组织成JSON字符串   
	        JSONStringer stringer = new JSONStringer();  
	        try{  
	            stringer.array();   
	            stringer.object();
	            stringer.key("barcode").value(book.getBarcode());
	            stringer.key("bookName").value(book.getBookName());
	            stringer.key("bookClassId").value(book.getBookClassId());
	            stringer.key("price").value(book.getPrice());
	            stringer.key("count").value(book.getCount());
	            stringer.key("publishDate").value(book.getPublishDate());
	            stringer.key("bookImage").value(book.getBookImage());
	            stringer.endObject();
	            stringer.endArray();  
	        }  
	        catch(Exception e){}  
	        response.getOutputStream().write(stringer.toString().getBytes("UTF-8"));  
	        response.setContentType("text/json; charset=UTF-8");  //JSON的类型为text/json
			
		} else if(action.equals("update")) {
			/*获取参数*/
			String barcode = new String(request.getParameter("barcode").getBytes("iso-8859-1"),"UTF-8"); 
			int bookClassId = Integer.parseInt(request.getParameter("bookClassId")); 
			String bookImage = new String(request.getParameter("bookImage").getBytes("iso-8859-1"),"UTF-8"); 
			String bookName = new String(request.getParameter("bookName").getBytes("iso-8859-1"),"UTF-8"); 
			int count = Integer.parseInt(request.getParameter("count")); 
			float price = Float.parseFloat(request.getParameter("price"));
			Timestamp publishDate = Timestamp.valueOf(request.getParameter("publishDate"));
		  
			/*封装对象*/
			Book book = new Book();
			book.setBarcode(barcode);
			book.setBookClassId(bookClassId);
			book.setBookImage(bookImage);
			book.setBookName(bookName);
			book.setCount(count);
			book.setPrice(price);
			book.setPublishDate(publishDate);
			
			/*调用业务层执行添加添加*/
			String result = bookDAO.UpdateBook(book); 
			response.setCharacterEncoding("utf-8");
			PrintWriter out = response.getWriter();
			out.print(result);
		}
		
	}

}
